package 二叉搜索树;

public class BSTree {
    public Node root = null;

    public void insert(int key){
        if (root == null){
            root = new Node(key);
            return;
        }

        Node parent = null;
        Node cur = root;
        while (cur != null){
            if (key == cur.key){
                throw new RuntimeException("key 重复了: " + key);
            }else if (key < cur.key){
                parent = cur;
                cur = cur.left;
            }else {
                parent = cur;
                cur = cur.right;
            }
        }

        // cur 就是 key 要插入的位置
        Node node = new Node(key);
        if (key < parent.key){
            parent.left = node;
        }else {
            parent.right = node;
        }
    }

    public boolean remove(int key){
        Node parent = null;
        Node cur = root;
        while (cur != null){
            if (key == cur.key){
                removeNode(parent, cur);
                return true;
            }else if (key < cur.key){
                parent = cur;
                cur = cur.left;
            }else {
                parent = cur;
                cur = cur.right;
            }
        }
        return false;
    }

    private void removeNode(Node parent, Node cur) {
        if (cur.left == null){
            if (cur == root){
                root = cur.right;
            }else if (cur == parent.left){
                parent.left = cur.right;
            }else {
                parent.right = root.right;
            }
        }else if (cur.right == null){
            if (cur == root){
                root = cur.left;
            }else if (cur == parent.left){
                parent.left = cur.left;
            }else {
                parent.right = cur.left;
            }
        }else {
            Node nextParent = cur;
            Node next = cur.right;
            while (next.left != null){
                nextParent = next;
                next = next.left;
            }

            cur.key = next.key;

            if (nextParent == cur){
                nextParent.right = next.right;
            }else {
                nextParent.left = next.right;
            }
        }
    }

    // o(树的高度)
    public boolean find(int key){
        Node cur = root;
        while (cur != null){
            if (key == cur.key){
                return true;
            }else if (key < cur.key){
                cur = cur.left;
            }else {
                cur = cur.right;
            }
        }
        return false;
    }

    private static void inorder(Node node){
        if (node != null){
            inorder(node.left);
            System.out.print(node.key + " ");
            inorder(node.right);
        }
    }

    private static void postorder(Node node){
        if (node != null){
            postorder(node.left);
            postorder(node.right);
            System.out.print(node.key + " ");
        }
    }

}
